const path = require('path');
const fs = require('fs');
const _ = require('lodash');
const config = require('./../config/config');

/**
 * 同步创建文件目录
 * @param  {string} dirname 目录绝对地址
 * @return {boolean}        创建目录结果
 */
function mkdirsSync(dirname) {
    if (fs.existsSync(dirname)) {
        return true
    } else {
        if (mkdirsSync(path.dirname(dirname))) {
            fs.mkdirSync(dirname);
            return true
        }
    }
}

/**
 * 获取上传文件的后缀名
 * @param  {string} fileName 获取上传文件的后缀名
 * @return {string}          文件后缀名
 */
function getSuffixName(fileName) {
    // let nameList = fileName.split('.');
    // return nameList[nameList.length - 1]
    return path.extname(fileName)
}


/**
 * 上传文件
 * @param  {object} ctx     koa上下文
 * @param  {object} options 文件上传参数 fileType文件类型， path文件存放路径
 * @return {promise}
 */
function uploadFile(ctx, options) {


    return new Promise((resolve, reject) => {
        console.log('文件上传中...');
        let result = {
            success: false,
            data: null
        };

        try {
            let body = ctx.request.body;
            let filePath = options.path;
            let files = body.files;
            //创建文件夹目录
            mkdirsSync(filePath);
            let filePaths = [];
            _(files).forEach(file => {
                let newPath = path.join(filePath, file.name);
                filePaths.push(newPath);
                let stream = fs.createWriteStream(newPath);
                fs.createReadStream(file.path).pipe(stream);
            });
            result.status = 'success';
            result.data = filePaths;
            resolve(result);
            return result;
        } catch (e) {
            reject(e)
        }
    })

}

function readFileToData(path) {
    return new Promise((resolve, reject) => {
        fs.readFile(path, function (err, data) {
            if (err) {
                reject(err);
            } else {
                resolve(data)
            }
        })

    }).then(function (data) {
        return data
    }).then(function (err) {
        return err
    })
}

function getFileNameForPath(path) {
    let start = path.lastIndexOf('\\');
    return path.substring(~~start + 1)
}

/**
 * 将 获取到的Url的别名转换为服务器真实地址
 * @param url
 * @returns {string}
 */

function getRealUrl(url) {
    let dirs = config.basicDir;
    for (let i = 0; i < dirs.length; i++) {
        let dir = dirs[i];
        if (url.startsWith(dir.name)) {
            //处理中文被url encode编码
            let offset = decodeURIComponent(url.substr(dir.name.length));
           return dir.path + offset;
        }
    }
}

function remove(path) {
    let files = [];
    if(fs.existsSync(path)) {
        if(fs.statSync(path).isDirectory()) {
            files  = fs.readdirSync(path);
            files.forEach(function(file){
                let curPath = path + '/' + file;
                if (fs.statSync(curPath).isDirectory()) {
                    remove(curPath);
                } else {
                    fs.unlinkSync(curPath)
                }
            });
            fs.rmdirSync(path)
        }else {
            fs.unlinkSync(path)
        }
    }
}


module.exports = {
    mkdirsSync,
    getSuffixName,
    uploadFile,
    readFileToData,
    getFileNameForPath,
    getRealUrl,
    remove
};